package org.testis.gui.mvc.controller.testdesign;

import org.testis.gui.mvc.controller.*;
import org.testis.gui.mvc.model.testdesign.LanguageVariablesModel;
import org.testis.gui.mvc.utilities.AtofTableModel;
import org.testis.gui.mvc.view.testdesign.LanguageVariablesView;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.testis.orm.classes.T_dmap_languages;
import org.testis.orm.refinedclasses.TestDesignTreeNode;
import org.testis.orm.refinedclasses.TestDesignTreeRefined.TestDesignTreeParameters;
import org.testis.utils.middleware.LanguageDataHandler;

/**
 *
 * @author nurhat
 */
public class LanguageVariablesController extends AbstractController {

    public static final String SELECT_LANGUAGE_ID = "LanguageId";
    public static final String SELECT_LANGUAGE_VARIABLE = "LanguageVariable";
    public static final String SHOW_VIEW = "ViewVisibility";
    public static final String SHOW_ERROR = "LastError";
    public static final String PARAMETER_MODEL_CHANGED = "Model";

    public void startLoader() {
        Integer langId = getSelectedLanguageId();
        if (!isValidLanguage(langId)) {
            return;
        }
        initialize();
        checkCurrentTestPlan();
        setModelProperty(SHOW_VIEW,
                true);
    }

    public void startLoader(int deviceAbstraction) {
        LanguageDataHandler handler = new LanguageDataHandler();
        T_dmap_languages[] langs = handler.getLanguagesByDeviceAbstractionId(
                deviceAbstraction);
        if (langs.length > 0) {
            if (!isValidLanguage(langs[0].getId())) {
                return;
            }
            initialize();
            operationLoadLanguage(langs[0].getId());
            setModelProperty(SHOW_VIEW,
                    true);
        } else {
            TestDesignControllerList.newInstance().getTreeController().
                    operationGenerateErrorMessage(
                    "No language found for the current device abstraction group...",
                    "Error");
        }
    }

    public Integer getSelectedLanguageId() {
        TestDesignTreeNode node = TestDesignControllerList.newInstance().
                getTreeController().getSelectedTreeNode();
        TestDesignTreeNode testPlanNode = findTestPlan(node);
        if (testPlanNode != null) {
            Integer languageId = testPlanNode.getReference().getParameterIntValue(TestDesignTreeParameters.LanguageId.name());
            if (languageId != null) {
                return languageId;
            }
        }
        return 0;
    }

    public boolean isValidLanguage(Integer langId) {

        if (langId != null) {
            if (langId != 0) {
                LanguageDataHandler handler = new LanguageDataHandler();
                if (handler.getLanguageById(langId) != null) {
                    return true;
                } else {
                    TestDesignControllerList.newInstance().getTreeController().
                            operationGenerateErrorMessage(
                            "Language selected for testplan deleted. Please select another language...",
                            "Error");
                }
            } else {
                TestDesignControllerList.newInstance().getTreeController().
                        operationGenerateErrorMessage(
                        "Please select a testplan to use language variables...",
                        "Error");
            }
        } else {
            TestDesignControllerList.newInstance().getTreeController().
                    operationGenerateErrorMessage(
                    "No language defined for the selected test plan...",
                    "Error");
        }
        return false;
    }

    public void initialize() {
        AtofTableModel temp = new AtofTableModel();
        temp.addColumn("Id");
        temp.addColumn("Name");
        LanguageVariablesModel m = new LanguageVariablesModel(temp);
        LanguageVariablesView v = new LanguageVariablesView(
                DynamicMapControllerList.newInstance().getParentFrame(),
                true);
        super.addModel(m);
        super.addView(v);
        v.pack();


    }

    public void operationCloseWindow() {
        this.cleanAll();
    }

    public void operationChangeLanguageVariable(String val) {

        String value = TestDesignControllerList.newInstance().
                getDataObjectController().operationGetValue();
        if (value == null) {
            value = "";
        } else if (!value.equals("")) {
            value = value + " ";
        }
        TestDesignControllerList.newInstance().getDataObjectController().
                operationChangeValue(value + "@LANG_" + val + "@");
        DynamicMapControllerList.newInstance().getDynamicMapController().
                operationChangeValueForLanguageVariable("@LANG_" + val + "@");
        ConditionTextEditorController.createInstance().operationSetConditionText( ConditionTextEditorController.createInstance().operationGetConditionText()+"@LANG_" + val + "@");
        setModelProperty(SELECT_LANGUAGE_VARIABLE,
                val);
    }

    public void operationChangeLanguageId(Integer val) {
        setModelProperty(SELECT_LANGUAGE_ID,
                val);
    }

    private void operationLoadLanguage(Integer langId) {
        if (langId != null) {
            setModelProperty(SELECT_LANGUAGE_ID,
                    langId);
            HashMap hmap = TestDesignControllerList.newInstance().
                    getLanguageHandlerController().operationParseLanguagePairs(
                    langId,
                    false);
            AtofTableModel temp = new AtofTableModel();
            temp.addColumn("Id");
            temp.addColumn("Name");
            Iterator iter = hmap.entrySet().
                    iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String[] keyVal = new String[2];
                keyVal[0] = entry.getKey().toString();
                keyVal[1] = entry.getValue().toString();
                temp.addRow(keyVal);


            }
            setModelProperty(PARAMETER_MODEL_CHANGED,
                    temp);
        } else {
            setModelProperty(SHOW_ERROR,
                    "Language not found....");
        }
    }

    private void checkCurrentTestPlan() {
        Integer langId = getSelectedLanguageId();
        if (langId != null) {
            setModelProperty(SELECT_LANGUAGE_ID,
                    langId);
            HashMap hmap = TestDesignControllerList.newInstance().
                    getLanguageHandlerController().operationParseLanguagePairs(
                    langId,
                    false);
            AtofTableModel temp = new AtofTableModel();
            temp.addColumn("Id");
            temp.addColumn("Name");
            Iterator iter = hmap.entrySet().
                    iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String[] keyVal = new String[2];
                keyVal[0] = entry.getKey().toString();
                keyVal[1] = entry.getValue().toString();
                temp.addRow(keyVal);


            }
            setModelProperty(PARAMETER_MODEL_CHANGED,
                    temp);
        } else {
            setModelProperty(SHOW_ERROR,
                    "You have to select language for current test plan");
        }
    }

    private TestDesignTreeNode findTestPlan(TestDesignTreeNode node) {
        if (node == null) {
            return null;
        } else if (node.getReference().getType().getName().equals("TestPlan")) {
            return node;
        }


        return findTestPlan(node.getParent());

    }
}
